var express = require('express');
var glob = require('glob');

var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var compress = require('compression');
var methodOverride = require('method-override');
var engines = require('../engine/index');
var webpack = require('webpack');
var webpackMiddleware = require("webpack-dev-middleware");
var proxy = require('express-http-proxy');
var _ = require('lodash');

module.exports = function (app, config) {
    var env = process.env.NODE_ENV || 'development';
    app.locals.ENV = env;
    app.locals.ENV_DEVELOPMENT = env == 'development';

    // app.set('views', config.root + '/app/views');
    // app.set('view engine', 'ejs');

    // view engine setup
    app.set('views', config.viewsPath);
    app.set('view engine', 'vm');
    app.engine('vm', engines.vm);

    // app.use(favicon(config.root + '/public/img/favicon.ico'));
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
        extended: true
    }));
    app.use(cookieParser());
    app.use(compress());
    app.use(express.static(config.root + config.staticPath));
    app.use(methodOverride());
    if(_.has(config,'proxy')){
        app.use(config.proxyPath, proxy(config.proxy,{
            forwardPath: function(req, res) {
                return config.proxyPath + require('url').parse(req.url).path;
            }
        }));
    }
//http://localhost:3000/api/wap/queryContractInfoPageList.json


    var controllers = glob.sync(config.root + '/app/controllers/*.js');
    controllers.forEach(function (controller) {
        require(controller)(app);
    });
    require('../config/router')(app,config);

    var webpackConf = require('../webpack-dev.config');
    var compiler = webpack(webpackConf);

    app.use(webpackMiddleware(compiler, webpackConf.devServer));
    app.use(require("webpack-hot-middleware")(compiler));
    

    app.use(function (req, res, next) {
        var err = new Error('Not Found');
        err.status = 404;
        next(err);
    });

    if (app.get('env') === 'development') {
        app.use(function (err, req, res, next) {
            res.status(err.status || 500);
            res.render('default/error', {
                message: err.message,
                error: err,
                title: 'error'
            });
        });
    }

    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('default/error', {
            message: err.message,
            error: {},
            title: 'error'
        });
    });

};
